#pragma once
#include <iostream>
#include "oj_model.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "oj_view.hpp"
#include <mutex>
#include <vector>
#include <assert.h>
#include <fstream>
#include <algorithm>
#include <jsoncpp/json/json.h>
#include "../comm/httplib.h"
namespace ns_control
{
    using namespace ns_model;
    using namespace ns_log;
    using namespace ns_util;
    using namespace std;
    using namespace ns_view;
    using namespace httplib;
    // 连接的主机
    class Machine
    {
    public:
        Machine()
            : ip(""), port(0), load(0), mtx(nullptr)
        {
        }

        ~Machine()
        {
            // if (mtx)
            // {
            //     delete mtx;
            //     mtx = nullptr;
            // }
        }

        // 禁止拷贝构造
        // Machine(const Machine &) = delete;
        // 禁止赋值操作
        // Machine &operator=(const Machine &) = delete;

        ////////////////////////////////////////////////////////////
        // 移动构造函数
        // Machine(Machine &&other) noexcept
        //     : ip(std::move(other.ip)),
        //       port(other.port),
        //       load(other.load),
        //       mtx(other.mtx)
        // {
        //     other.port = 0;
        //     other.load = 0;
        //     other.mtx = nullptr;
        // }

        // 移动赋值运算符
        // Machine &operator=(Machine &&other) noexcept
        // {
        //     if (this != &other)
        //     {
        //         ip = std::move(other.ip);
        //         port = other.port;
        //         load = other.load;
        //         mtx = other.mtx;
        //         other.port = 0;
        //         other.load = 0;
        //         other.mtx = nullptr;
        //     }
        //     return *this;
        // }
        ////////////////////////////////////////////////////////////
        void loadincrease()
        {
            if (mtx)
                mtx->lock();
            load++;
            if (mtx)
                mtx->unlock();
        }

        void loaddecrease()
        {
            if (mtx)
                mtx->lock();
            load--;
            if (mtx)
                mtx->unlock();
        }

        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }

        void resetload()
        {
            if (mtx)
                mtx->lock();

            load = 0;
            if (mtx)
                mtx->unlock();
        }

    public:
        std::string ip;  // 编译服务的ip
        int port;        // 编译服务的port
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // mutex禁止拷贝的
    };
    const std::string machine_list = "./conf/service_machine.conf";
    // 负载均衡
    class LoadBlance
    {
    public:
        LoadBlance()
        {
            // 主机加载
            assert(LoadConf(machine_list));
            LOG(INFO) << "加载" << machine_list << "成功";
        }

        ~LoadBlance()
        {
        }
        // 主机加载
        bool LoadConf(const std::string machine_list)
        {
            ifstream in(machine_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "获取主机文件列表失败";
                return false;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<string> tokens;
                StringUtill::SplitSpring(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败";
                    continue;
                }
                Machine M;
                M.ip = tokens[0];
                M.port = atoi(tokens[1].c_str());
                std::cout << M.ip << ": " << M.port << std::endl; 
                M.load = 0;
                M.mtx = new std::mutex();
                machines.push_back(M);// 先插入在记录下标
                online.push_back(machines.size() - 1);
                
                //machines.push_back(move(M));
            }
            in.close();
            return true;
        }

        // 选择负载最小的主机
        bool Smartchioce(int *id, Machine **m)
        {
            mtx.lock();

            int online_num = online.size();
            if (online.size() == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "后端主机全部离线";
                return false;
            }

            *id = online[0];
            *m = &machines[online[*id]]; ///////online[0]///////////////////////////////////
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 1; i < online_num; i++)
            {
                uint64_t tmp = machines[online[0]].Load();
                if (min_load > tmp)
                {
                    min_load = tmp;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }

            mtx.unlock();
            return true;
        }

        void OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), unline.begin(), unline.end());
            unline.erase(unline.begin(), unline.end());
            mtx.unlock();
            LOG(INFO) << "所有主机已经加载完成";
        }

        void unlineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].resetload();
                    online.erase(iter);
                    unline.push_back(0);
                    break;
                }
            }
            mtx.unlock();
        }

    private:
        // 提供编译大的所有主机，以下标为媒介进行访问
        vector<Machine> machines;
        // 所有的在线主机
        vector<int> online;
        // 所有离线主机
        vector<int> unline;

        std::mutex mtx;
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBlance _load_blance;

    public:
        Control()
        {
        }
        ~Control()
        {
        }

        void RecoverMachine()
        {
            _load_blance.OnlineMachine();
        }
        // 获取所有题目信息并形成网页
        bool AllQuestions(std::string *html)
        {
            bool ret = true;
            vector<struct Question> q;
            if (_model.GetAllQuestions(&q))
            {
                sort(q.begin(), q.end(), [](const struct Question &q1, const struct Question &q2)
                     { return atoi(q1.number.c_str()) < atoi(q2.number.c_str()); });
                _view.AllExpendhtml(q, html);
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
            }
            return ret;
        }
        // 获取指定题目信息并形成网页
        bool Question(const std::string &number, std::string *html)
        {
            bool ret = true;
            struct Question q;
            if (_model.GetOneQuestions(number, &q))
            {
                _view.OneExpendhtml(q, html);
            }
            else
            {
                *html = "获取题目失败，形成题目信息失败";
                ret = false;
            }
            return ret;
        }
        // 对用户提交的代码进行判题
        void judge(const std::string number, const std::string in_json, std::string *out_json)
        {
            // 0. 获取题目信息，拿到具体细节
            struct Question q;
            _model.GetOneQuestions(number, &q);
            // 1. in json进行反序列化，得到题目的id，
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();
            // 2. 得到用户提交源代码，input重新拼接用户代码+测试用例代码，
            Json::Value compile_value;
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["input"] = in_value["input"].asString();
            compile_value["cpu_limit"] = q.cpu_limt;
            compile_value["mem_limit"] = q.mem_limt;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 3. 形成新的代码选择负载最低的主机(差错处理),
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_blance.Smartchioce(&id, &m))
                {
                    break;
                }
                LOG(INFO) << "主机选择成功" << "ip:" << m->ip << "port" << m->port << "\n";
                // 4. 然后发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->loadincrease();
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 5. 将结果赋值给out来自于_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->loaddecrease();
                        LOG(INFO) << "编译运行成功...";
                        break;
                    }
                    m->loaddecrease();
                }
                else
                {
                    // 请求主机失败
                    LOG(Error) << "主机链接编译运行失败，可能已经离线" << "m.ip" << m->ip;
                    // m->loadincrese();
                    _load_blance.unlineMachine(id);
                }
            }
        }
    };
}
